<template>
  <div id="labCompanyFeeitemDiv">
    <Splitpanes>
      <Pane size="30">
        <Splitpanes horizontal class="horizontalLine">
          <Pane size="50">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-input style="width: 180px" v-model="searchCompanyFeeForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findCompanyUserList" @keyup="keyupCompanyFeeEnter" @search-click="findCompanyUserList()"></vxe-input>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="ploading" @click="findCompanyUserList"></vxe-button>
                <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchCompanyUser"></vxe-button>
                <!-- <div class="msgDiv">双击移除</div> -->
              </template>
            </vxe-toolbar>
            <div class="rightTable">
              <vxe-table ref="tatItemTableRef" :data="companyUserList" :loading="ploading" @current-change="companySalesmanRowClick" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
                <vxe-column type="checkbox" width="30"></vxe-column>
                <vxe-column field="companyCode" title="单位编码" width="90"></vxe-column>
                <vxe-column field="companyName" title="单位名称" min-width="180"></vxe-column>
              </vxe-table>
            </div>
          </Pane>
          <Pane size="50">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-input style="width: 180px" v-model="searchForm.seachValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findCompanyList" @keyup="keyupEnter" @search-click="findCompanyList()"></vxe-input>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="floading" @click="findCompanyList"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="rightTable">
              <vxe-table ref="feeItemTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="companyList" :loading="floading" @cell-dblclick="userRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                <vxe-column type="seq" title="#" width="30"></vxe-column>
                <vxe-column field="companyCode" title="单位编码" width="90"></vxe-column>
                <vxe-column field="companyName" title="单位名称" min-width="180"></vxe-column>
              </vxe-table>
            </div>
          </Pane>
        </Splitpanes>
      </Pane>
      <Pane size="70">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="sloading" @click="findSalesFeeItemList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveSalesFeeitemList"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="rightTable">
          <!--@cell-dblclick="tatItemRowClick"   双击移除-->
          <vxe-table ref="salesFeeItemTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="salesFeeItemList" :loading="sloading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column type="seq" title="#" width="30"></vxe-column>
            <vxe-column field="feeCode" title="项目编号" width="80"></vxe-column>
            <vxe-column field="feeName" title="项目名称" min-width="100"></vxe-column>
            <vxe-column field="origPrice" title="原价" min-width="100"></vxe-column>
            <vxe-column field="discount" title="折扣" min-width="100"></vxe-column>
            <vxe-column field="price" title="折扣价" min-width="100"></vxe-column>
            <vxe-column field="brokerageType" title="佣金方式" width="80" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatCommon(transKindList, row.brokerageType) }}</span>
              </template>
              <template #edit="{ row, rowIndex, column }">
                <!-- 选择字典  -->
                <vxe-select v-model="row.brokerageType">
                  <vxe-option v-for="hobj in transKindList" :key="hobj.code" :value="hobj.code" :label="hobj.name"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>

            <vxe-column field="brokerage" title="佣金值" width="80" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.brokerage" placeholder="" type="float" :min="0" :max="1" @blur="funDiscountPrice1(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="brokerageCosts" title="销售提成" min-width="100" :edit-render="{}">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.brokerageCosts" placeholder="" type="number"></vxe-input>
              </template>
            </vxe-column>

          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty } from '@/utils/common'; //'../../../stores/store';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
defineExpose({ initPage });
let inspectSalesman: any = reactive({});
let sltCompanySalesman: any = reactive({});
let floading = ref(false);
let ploading = ref(false);
let sloading = ref(false);

let companyList = reactive([]);
let companyUserList = reactive([]);
let salesFeeItemList = reactive([]);

let searchForm = reactive({
  seachValue: ''
});
let searchCompanyFeeForm = {
  seachValue: ''
};
function initPage(row: any) {
  inspectSalesman = row;
  findCompanyUserList();
  findCompanyList();
}
let transKindList: any = reactive([
  { code: '1', name: '按比例' },
  { code: '2', name: '固定值' }
]);
function keyupCompanyFeeEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findCompanyUserList();
  }
}
function findCompanyUserList() {
  ploading.value = true;
  companyUserList.length = 0; //放入数据前清空数据
  const url = '/lab/inspectCompanySalesman/findInspectCompanySalesmanList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchCompanyFeeForm.seachValue,
        salemanCode: inspectSalesman.code
      }
    })
    .then((res: any) => {
      companyUserList.push(...res.data);
      if (companyUserList.length == 0) {
        sltCompanySalesman = {};
        salesFeeItemList.length = 0;
      } else {
        const kn = companyUserList.find((k: any) => k.id == sltCompanySalesman.id);
        if (IsEmpty(kn)) {
          companySalesmanRowClick({ row: companyUserList[0] }); //默认选中第一条数据
        } else {
          companySalesmanRowClick({ row: kn }); //默认选中第一条数据
        }
      }
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function companySalesmanRowClick({ row }: any) {
  if (IsEmpty(row)) {
    sltCompanySalesman = {};
    //settleDetailList.length = 0;
  } else {
    (proxy.$refs.tatItemTableRef as any)?.setCurrentRow(row);
    sltCompanySalesman = row;
    //查询新表数据
    findSalesFeeItemList();
  }
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findCompanyList();
  }
}

function findCompanyList() {
  floading.value = true;
  companyList.length = 0; //放入数据前清空数据
  const url = '/lab/inspectCompany/findCompanyBySalesmanList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        keywords: searchForm.seachValue
      }
    })
    .then((res: any) => {
      companyList.push(...res.data);

      floading.value = false;
    })
    .catch((err: any) => {
      floading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function userRowClick({ row }: any) {
  if (IsEmpty(inspectSalesman)) {
    VxeMessage('请选择销售人员', VxeNotifyType.error);
    return;
  }
  const url = '/lab/inspectCompanySalesman/addCompanySalesman';
  let purposeItem = {
    code: inspectSalesman.code,
    name: inspectSalesman.name,
    companyId: row.id,
    companyCode: row.companyCode,
    companyName: row.companyName
  };
  proxy.$http
    .post(url, purposeItem)
    .then((res: any) => {
      VxeMessage('成功', VxeNotifyType.success);
      findCompanyUserList();
      findCompanyList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function deleteBatchCompanyUser() {
  const sltTatItems = (proxy.$refs.tatItemTableRef as any).getCheckboxRecords();
  if (!(sltTatItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const url = '/lab/inspectCompanySalesman/batchDeleteCompanySalesmanList';
        proxy.$http
          .post(url, sltTatItems)
          .then((res: any) => {
            if (res.status.code === 1) {
              findCompanyUserList();
              findCompanyList();
              VxeMessage('删除成功', VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function findSalesFeeItemList() {
  sloading.value = true;
  salesFeeItemList.length = 0; //放入数据前清空数据
  const url = '/lab/financeSalesFeeitem/findSalesFeeItemList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        salesmanCode: sltCompanySalesman.code,
        companyCode: sltCompanySalesman.companyCode
      }
    })
    .then((res: any) => {
      salesFeeItemList.push(...res.data);
      sloading.value = false;
    })
    .catch((err: any) => {
      sloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}
function saveSalesFeeitemList() {
  if (salesFeeItemList.length > 0) {
    const url = '/lab/financeSalesFeeitem/saveBatchSalesFeeitem';
    const obj: any = {};
    obj.salesmanCode = sltCompanySalesman.code;
    obj.companyCode = sltCompanySalesman.companyCode;
    obj.financeSalesFeeitemList = salesFeeItemList;
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        VxeMessage('更新成功', VxeNotifyType.success);
        setTimeout(() => {
          findSalesFeeItemList();
        }, 50);
      })
      .catch((err: any) => {
        VxeMessage('更新失败', VxeNotifyType.success);
      });
  } else {
    VxeMessage('无添加或修改数据', VxeNotifyType.error);
  }
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

function funDiscountPrice1(row: any) {
  //按照比例
  if (row.brokerageType == '1') {
    if (!IsEmpty(row.brokerage)) {
      row.brokerageCosts = parseFloat(String(row.price * row.brokerage)).toFixed(2);
    }
  }
}
</script>

<style lang="scss" scoped>
#labCompanyFeeitemDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .rightTable {
    height: calc(100% - 40px);
  }
}
</style>